package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import model.AllItem;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utils.Utils;
import utils.XmlParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import app.cloudstringers.Home;
import app.cloudstringers.Login;
import app.cloudstringers.MyVideoTab;
import app.cloudstringers.R;
import define.API;
import define.Constants;
import define.DefaultValue;
import define.Key;
import define.SharedPreference;

public class AllTabsAsync extends AsyncTask<Integer, Void, Boolean> {
	/**
	 * String section
	 */
	private int SELLING_INDEX = 0;

	// XML node keys
	private static final String KEY_ASSOCIATION = "ASSOCIATION";
	private static final String KEY_CAMCORDER_MODEL = "CAMCORDER_MODEL";
	private static final String KEY_CITY = "CITY";
	private static final String KEY_CURRENT_SIZE = "CURRENTSIZE";
	private static final String KEY_FILE = "FILE"; // parent node
	private static final String KEY_FILE_NAME = "FILENAME";
	private static final String KEY_JOURNALIST_ID = "JOURNALIST_ID";
	private static final String KEY_MEMO = "MEMO";
	private static final String KEY_SELLING = "SELLING";
	private static final String KEY_SHOT_ID = "SHOT_ID";
	private static final String KEY_TOTAL_SIZE = "TOTALSIZE";
	private static final String KEY_UPLOAD_TIME = "UPLOADTIME";

	private String ASSOCIATION = null, CAMCODER_MODEL = null, CITY = null,
			CURRENT_SIZE = null, FILE_NAME = null, ID = null,
			JOURNALIST_ID = null, MEMO = null, SELLING = null, SHOT_ID = null,
			TOTAL_SIZE = null, UPLOAD_TIME = null;

	private static final String TAG = AllTabsAsync.class.getSimpleName();

	/**
	 * Data section
	 */
	public static ArrayList<AllItem> mAlAllItem = new ArrayList<AllItem>();
	public static ArrayList<AllItem> mAlAuctionItem = new ArrayList<AllItem>();
	public static ArrayList<AllItem> mAlMarketPlaceItem = new ArrayList<AllItem>();
	public static ArrayList<AllItem> mAlPrivacyItem = new ArrayList<AllItem>();

	/**
	 * View section
	 */
	private AlertDialog.Builder mAdLogin;

	/**
	 * Other section
	 */
	private Utils connectivity;
	private Context context;
	public static SharedPreferences mSpSettings;
	public static SharedPreferences.Editor mSpEditor;
	private XmlParser mXMLParser;

	public AllTabsAsync(Context context) {
		this.context = context;

		connectivity = new Utils(context);

		// Get shared preferences
		mSpSettings = context.getSharedPreferences(SharedPreference.PREFS,
				Context.MODE_PRIVATE);
		mSpEditor = mSpSettings.edit();

		// new GetTokenString(context, true).execute();
	}

	@Override
	protected Boolean doInBackground(Integer... params) {
		// Get token string
		// Get data from status_upload.php
		HttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mHttpPost = new HttpPost(API.UPLOAD_STATUS);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

		nameValuePairs.add(new BasicNameValuePair(Key.KEY_GLOBAL_ID, ID));
		nameValuePairs.add(new BasicNameValuePair(Key.KEY_STATE,
				Constants.STATE_DONE + ""));

		try {
			mHttpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			// Log.i(TAG, XML);

			mXMLParser = new XmlParser();
			Document mDocument = mXMLParser.getDomElement(XML);

			NodeList mNodeList = mDocument.getElementsByTagName(KEY_FILE);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) mNodeList.item(i);

					// Get data from the server follow the Key
					ASSOCIATION = mXMLParser.getValue(element, KEY_ASSOCIATION);
					CAMCODER_MODEL = mXMLParser.getValue(element,
							KEY_CAMCORDER_MODEL);
					CITY = mXMLParser.getValue(element, KEY_CITY);
					CURRENT_SIZE = mXMLParser.getValue(element,
							KEY_CURRENT_SIZE);
					FILE_NAME = mXMLParser.getValue(element, KEY_FILE_NAME);
					JOURNALIST_ID = mXMLParser.getValue(element,
							KEY_JOURNALIST_ID);
					MEMO = mXMLParser.getValue(element, KEY_MEMO);
					SELLING = mXMLParser.getValue(element, KEY_SELLING);
					SHOT_ID = mXMLParser.getValue(element, KEY_SHOT_ID);
					UPLOAD_TIME = mXMLParser.getValue(element, KEY_UPLOAD_TIME);
					TOTAL_SIZE = mXMLParser.getValue(element, KEY_TOTAL_SIZE);
					
					SELLING_INDEX = Integer.parseInt(SELLING);

					if (MyVideoTab.CURRENT_TAB == 0) {
						checkCurrentTab();
					} else {
						checkCurrentTab(SELLING_INDEX);
					}
				}
			}

			// Reverse the list item for see new things
			Collections.reverse(mAlAllItem);

			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// Show progress dialog
		connectivity.showProgressDialog();

		initialAlertDialogs();

		if (!mAlAllItem.isEmpty())
			mAlAllItem.clear();
		if (!mAlAuctionItem.isEmpty())
			mAlAuctionItem.clear();
		if (!mAlMarketPlaceItem.isEmpty())
			mAlMarketPlaceItem.clear();
		if (!mAlPrivacyItem.isEmpty())
			mAlPrivacyItem.clear();

		// Get ID from shared preference
		ID = mSpSettings.getString(SharedPreference.PREFS_KEY_GLOBAL_ID,
				DefaultValue.DEFAULT_GLOBAL_ID + "");

		// If wrong ID, show login dialog
		if (ID.equals(DefaultValue.DEFAULT_GLOBAL_ID)) {
			mAdLogin.show();
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if (!result) {
			Constants.utils.showConnectionTimeoutDialog(context,
					Home.class);
		}

		connectivity.hideProgressDialog();
	}

	/**
	 * Initial methods
	 */
	private void initialAlertDialogs() {
		mAdLogin = new AlertDialog.Builder(context);
		mAdLogin.setTitle(context.getString(R.string.title_login));
		mAdLogin.setCancelable(false);
		mAdLogin.setMessage(context.getString(R.string.content_login));
		mAdLogin.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						mSpEditor.putString(
								SharedPreference.PREFS_KEY_USER_NAME, "user");
						mSpEditor.putString(
								SharedPreference.PREFS_KEY_GLOBAL_ID,
								DefaultValue.DEFAULT_GLOBAL_ID + "");
						mSpEditor.commit();

						// new Intent to login class
						Intent intent = new Intent(context, Login.class);
						((Activity) context).finish();
						context.startActivity(intent);
					}
				});
	}

	/**
	 * Basic methods
	 */
	/**
	 * Check current tab
	 */
	private void checkCurrentTab() {
		AllItem all_item = new AllItem(SELLING_INDEX, ASSOCIATION,
				CAMCODER_MODEL, CITY, CURRENT_SIZE, FILE_NAME, JOURNALIST_ID,
				MEMO, SHOT_ID, TOTAL_SIZE, UPLOAD_TIME);
		mAlAllItem.add(0, all_item);
	}

	private void checkCurrentTab(int sellingIndex) {
		switch (sellingIndex) {
		case 0:
			AllItem privacy_item = new AllItem(sellingIndex, ASSOCIATION,
					CAMCODER_MODEL, CITY, CURRENT_SIZE, FILE_NAME,
					JOURNALIST_ID, MEMO, SHOT_ID, TOTAL_SIZE, UPLOAD_TIME);
			mAlPrivacyItem.add(privacy_item);
			break;
		case 1:
			AllItem auction_item = new AllItem(sellingIndex, ASSOCIATION,
					CAMCODER_MODEL, CITY, CURRENT_SIZE, FILE_NAME,
					JOURNALIST_ID, MEMO, SHOT_ID, TOTAL_SIZE, UPLOAD_TIME);
			mAlAuctionItem.add(auction_item);
			break;
		case 2:
			AllItem market_place_item = new AllItem(sellingIndex, ASSOCIATION,
					CAMCODER_MODEL, CITY, CURRENT_SIZE, FILE_NAME,
					JOURNALIST_ID, MEMO, SHOT_ID, TOTAL_SIZE, UPLOAD_TIME);
			mAlMarketPlaceItem.add(market_place_item);
			break;
		default:
			break;
		}
	}
}
